<template>
	<view class="home contanter">
		<up-toast ref="uToastRef"></up-toast>
		<u-navbar title="听单大厅" bgColor="#3C9CFF" rightIcon="bell-fill" @rightClick="handleSet" titleStyle="color:#fff" leftIconColor="transparent" placeholder></u-navbar>
		<view class="top">
			<sar-notice-bar>{{ notify }}</sar-notice-bar>
			<view class="total" @click="handleGo('/pages/index/offline')">
				<view class="item">
					<text>今日成单</text>
					<text class="num">{{money.todayOrderNum || 0}}</text>
				</view>
				<view class="item">
					<text>今日收入</text>
					<text class="num">{{money.todayOrderMoney || 0}}</text>
				</view>
				<view class="item">
					<text>本月收入</text>
					<text class="num">{{money.monthOrdeMoney || 0}}</text>
				</view>
			</view>
		</view>
		<view class="list">
			<up-empty v-if="!orderList || !orderList.length" mode="order" icon="http://cdn.uviewui.com/uview/empty/order.png"></up-empty>
			<view v-else class="orderlist" v-for="(item, index) in orderList" :key="index" @click="handleItem(item)">
				<view class="start">
					<text class="t">起：</text><text>{{item.startPlace}}</text>
				</view>
				<view class="end">
					<text class="t">终：</text><text>{{item.stopPlace}}</text>
				</view>
				<up-icon class="btn" name="arrow-right" color="#A6A6A6" size="14"></up-icon>
			</view>
		</view>
		<view class="btn-box">
			<view class="btn1" @click="handleQrcode">
				<up-icon class="icon1" name="order" size="26"></up-icon>
			</view>
			<up-button class="btn2" type="primary" :loading="statusLoading" @click="handleClick" :text="isOnline ? '停止听单' : '上线听单'" size="large"></up-button>
			<view class="btn3" @click="handleMap()"></view>
		</view>
		<!-- 正在进行中的订单 -->
		<view v-if="isOrdering" class="ordering" @click="handleGo('/pages/homeOrder/ordering')">
			<up-icon name="clock-fill" color="#2979ff" size="24"></up-icon>
		</view>
	</view>
</template>

<script setup>
	import http from "@/request/index.js"
	const isOnline = ref(false);
	const statusLoading = ref(false);
	const itemList = ref([
		{ icon: 'order', label: '订单', id: 1 },
		{ icon: 'star', label: '能力', id: 2 },
		{ icon: 'red-packet', label: '钱包', id: 3 },
		{ icon: 'hourglass', label: '检测', id: 4 }
	]);
	const orderList = ref([]);
	const money = ref({});
	const notify = ref('');
	const longitude = ref('');
	const latitude = ref('');
	const timer = ref(null);
	const isOrdering = ref(false);
	const ttsModule = ref(null);
	const uToastRef = ref(null)

	onMounted(() => {
		ttsModule.value = uni.requireNativePlugin("hm-tts-TtsModule");
		ttsModule.value.init((ret) => {})
		getStatus();
		getTopData();
		getList(1);
		getOrderingis(1);
	})
	const onPullDownRefresh = () => {
		getTopData();
		getStatus();
		getOrderingis();
	}
	
	// 保存经纬度
	async function getSaveLonLat(longitude, latitude) {
		if (!longitude || !latitude) {
			getApp().isLocationEnable()
			return
		}
		let driverId = uni.getStorageSync('authId');
		let { code, msg, data } = await http('/app/driver/saveCoordinate', { driverId, longitude, latitude }, 'POST')
		console.log('保存经纬度接口', code, msg, longitude, latitude)
		if (code != 200) return
		console.log(data, msg)
	}
	// 是否有正在进行中的订单
	async function getOrderingis() {
		let { code, msg, data } = await http('/app/order/getOrderFromInProgress', 'GET');
		if (code != 200) return (isOrdering.value = false)
		isOrdering.value = (data && data.id) ? true : false
	}
	// 消息通知
	async function getList(type) {
		let { code, msg, data } = await http(`/app/notice/queryPage`, {}, 'POST');
		if (code != 200) return
		notify.value = data.data && data.data.length ? data.data[0].noticeTitle : ''
	}
	// 司机是否上线状态
	async function getStatus() {
		let { code, msg, data } = await http('/app/driver/getDriverInfoByIsOnline', {}, 'GET');
		if (code != 200) return;
		isOnline.value = data.isOnline;
		if (data.isOnline) {
			longitude.value = getApp().globalData.longitude
			latitude.value = getApp().globalData.latitude
			// getSaveLonLat(longitude, latitude)
			getOrderList();
			timer.value && clearInterval(timer.value);
			timer.value = setInterval(() => { // 113.61302, 34.74811
				longitude.value = getApp().globalData.longitude
				latitude.value = getApp().globalData.latitude
				// console.log(123123123123, latitude, longitude)
				getOrderList();
				getSaveLonLat(longitude.value, latitude.value)
			}, 3000);
		} else {
			timer.value && clearInterval(timer.value);
			timer.value = null;
		}
	}
	// 获取今日成单今日收入本月收入等
	async function getTopData() {
		let { code, msg, data } = await http('/app/order/getOrderFromStatistic', {}, 'GET');
		uni.stopPullDownRefresh()
		if (code != 200) return
		money.value = data
	}
	// 实时订单列表
	async function getOrderList() {
		let { longitude, latitude } = this;
		let orderNumber = uni.getStorageSync('orderNumber');
		let { code, msg, data } = await http('/app/driver/getRealTimeOrder', { longitude, latitude }, 'POST');
		console.log(333, code);
		if (code != 200) return
		if (data.length > orderNumber) {
			ttsModule.value.speak({text: '来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~ 来新订单啦~'})
		}
		uni.setStorageSync('orderNumber', data.length);
		orderList.value = data;
	}
	const handleItem = (item) => {
		uni.navigateTo({
			url: '/pages/homeOrder/orderDetail?query=' + JSON.stringify(item)
		})
	}
	
	const handleSet = () => {
		// uni.navigateTo({
		// 	url: '/pages/index/notify'
		// })
		uni.navigateTo({
			url: '/pages/login/login'
		})
	}
	
	const handleGo = (url) => {
		uni.navigateTo({
			url
		})
	}
	
	const handleMap = () => {
		uni.navigateTo({
			url: '/pages/webview/drivermap'
		})
	}
	
	const handleQrcode = () => {
		uni.navigateTo({
			url: '/pages/index/qrCode'
		})
	}
	
	const handleNearDriver = () => {
		uni.navigateTo({
			url: '/pages/webview/drivermap'
		})
	}
	
	async function handleClick() {
		statusLoading.value = true;
		let onlineFlag = isOnline.value ? 2 : 1;
		let { longitude, latitude } = this;
		let { code, msg, data } = await http('/app/driver/updateDriverById', {
          longitude, latitude, onlineFlag
        }, 'POST');
		statusLoading.value = false;
		orderList.value = [];
		if (code != 200) return uToastRef.value.show({
			type: 'error',
			message: msg,
			duration: 4000
		})
		getStatus();
		uToastRef.value.show({
			type: 'success',
			message: onlineFlag == 1 ? '上线听单成功' : '停止听单成功',
		});
		var ret = ttsModule.value.speak({'text': onlineFlag == 1 ? '您已上线 ' : '您已下线 '})
	}
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		height: 100vh;
		background-color: #F7F7F7;
		overflow: auto;
		.top {
			width: 100%;
			height: 100px;
			background-color: #3C9CFF;
			color: #fff;
			position: relative;
			margin-top: -1px;
			.total {
				width: 100%;
				height: 70px;
				position: absolute;
				bottom: 1px;
				left: 0;
				.item {
					width: 33.3%;
					float: left;
					text-align: center;
					padding-top: 25px;
					overflow: hidden;
					text {
						display: block;
						width: 100%;
						overflow: hidden;
						font-size: 12px;
					}
					.num {
						font-weight: bold;
						font-size: 16px;
					}
				}
			}
			.setting {
				position: absolute;
				top: 10px;
				right: 20px;
			}
		}
		.list {
			width: 90%;
			height: calc(100% - 270px);
			margin: 10px auto;
			background-color: #fff;
			border-radius: 8px;
			overflow-y: auto;
			.orderlist {
				border-bottom: 1px solid #DCDDE0;
				padding: 15px 20px;
				position: relative;
				// color: #A6A6A6;
				.start, .end {
					.t {
						font-size: 12px;
						color: #EB0000;
					}
					text:last-child {
						display: inline-block;
						width: calc(100% - 40px);
						vertical-align: top;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
				.end {
					.t {
						color: #009609;
					}
				}
				.btn {
					position: absolute;
					right: 10px;
					top: 40%;
				}
			}
		}
		.btn-box {
			width: 90%;
			position: fixed;
			left: 5%;
			bottom: 10px;
			text-align: center;
			.btn1 {
				float: left;
				width: 50px;
				height: 50px;
				line-height: 55px;
				border-radius: 50%;
				box-shadow: 0px 0px 5px 3px rgba(0,0,0,0.1);
				text-align: center;
				background-color: #fff;
				.icon1 {
					display: inline-block;
				}
			}
			.btn2 {
				display: inline-block; 
				width: 200px;
				line-height: 50px;
			}
			.btn3 {
				box-shadow: 0px 0px 5px 3px rgba(0,0,0,0.1);
				float: right;
				width: 50px;
				height: 50px;
				border-radius: 50%;
				background: #fff url('./../../static/drive.png') 6px 5px no-repeat;
				background-size: 40px;
			}
		}
		.ordering {
			position: absolute;
			top: 30%;
			right: 30px;
			width: 40px;
			height: 40px;
			text-align: center;
			line-height: 45px;
			background-color: #fff;
			border-radius: 8px;
			box-shadow: 0px 0px 5px 5px rgba(0,0,0,.1);
			::v-deep .u-icon {
				display: inline-block;
			}
		}
		::v-deep .u-navbar__content__right .u-icon--right .u-icon__icon {
			color: #fff!important;
		}
	}
</style>